﻿using System;
using System.Windows.Forms;
using System.Reflection;

namespace UpwardsTimeClock.Prototype
{
    public partial class MainForm : Form
    {
        private ControlManager _controlManager;
        private DateTime _nextHourTime;
        private DateTime _nextHalfHourTime;
        private DateTime _nextQuarterHourTime;
        private DateTime _startTime;

        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
            DateTime now = DateTime.Now;
            DateTime thisHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
            TimeSpan oneHour = new TimeSpan(1,0,0);
            TimeSpan halfHour = new TimeSpan(0,30,0);
            TimeSpan quarterHour = new TimeSpan(0,15,0);
            TimeSpan threeQuarterHour = new TimeSpan(0,45, 0);
            const string TIME_FORMAT = "hh:mm tt";

            _nextHourTime = thisHour + oneHour;
            _nextHalfHourTime = thisHour + (now.Minute < 30 ?  halfHour : oneHour);
            _nextQuarterHourTime = thisHour +
                (now.Minute < 15 ? quarterHour :
                now.Minute < 30 ? halfHour :
                now.Minute < 45 ? threeQuarterHour : oneHour);

            StartOnTheHourRadioButton.Text = _nextHourTime.ToString(TIME_FORMAT);
            StartOnTheHalfHourRadioButton.Text = _nextHalfHourTime.ToString(TIME_FORMAT);
            StartOnTheQuarterHourRadioButton.Text = _nextQuarterHourTime.ToString(TIME_FORMAT);
            VersionLabel.Text = Application.ProductVersion;
        }

        void ControlManager_Finished(object sender, EventArgs e)
        {
            if (Program.Config.IsLooping)
            {
                // Re-load configuration when looping
                // http://code.google.com/p/upwards-time-clock/issues/detail?id=1

                // Clear out dynamic controls
                _controlManager.Dispose();
                MainPanel.Controls.Clear();

                // Re-load configuration
                Program.LoadConfig();

                // Re-create the ControlManager
                _controlManager = new ControlManager(Program.Config, MainPanel.Controls);
                _controlManager.Finished += ControlManager_Finished;
                _controlManager.Start(IncrementAndGetIteration());
            }
            else
            {
                Close();
            }
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            SetPanelSize();
        }

        private void SetPanelSize()
        {
            if (WindowState != FormWindowState.Minimized)
            {
                MainPanel.Left = (ClientRectangle.Width - MainPanel.Width) / 2;
                MainPanel.Top = (ClientRectangle.Height - MainPanel.Height) / 2;
            }
        }

        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            DialogResult result;

            switch (char.ToUpper(e.KeyChar))
            {
                case 'P':
                    _controlManager.Pause();
                    ShowMessage("Paused");
                    e.Handled = true;
                    break;
                case 'C':
                    _controlManager.Continue();
                    ShowMessage("Continued");
                    e.Handled = true;
                    break;
                case 'R':
                    result = MessageBox.Show(
                        this, "Are you sure you want to restart?",
                        "RESTART", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.Yes)
                    {
                        _controlManager.Start(ResetAndGetIteration());
                    }
                    e.Handled = true;
                    break;
                case 'L':
                    Program.Config.IsLooping = !Program.Config.IsLooping;
                    ShowMessage(Program.Config.IsLooping ? "Looping ON" : "Looping OFF");
                    e.Handled = true;
                    break;
                case 'S':
                    result = MessageBox.Show(
                        this, "Are you sure you want to stop?",
                        "STOP", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.Yes)
                    {
                        Program.Config.IsLooping = false;
                        _controlManager.Stop();
                    }
                    e.Handled = true;
                    break;
                case 'J':
                    StartSelectForm.ReturnValue returnValue =
                        StartSelectForm.SelectStartTime(numericIteration.Value);
                    if (returnValue != null)
                    {
                        numericIteration.Value = returnValue.Iteration;
                        _controlManager.Start(GetIteration(), returnValue.StartTime);
                        ShowMessage("Jumped");
                    }
                    e.Handled = true;
                    break;
                case 'H':
                    ShowMessage("[P]ause [C]ontinue\r\n[S]top [R]estart\r\n[J]ump [L]ooping", 5);
                    e.Handled = true;
                    break;
                default:
                    e.Handled = false;
                    break;
            }

        }

        private void ShowMessage(string message)
        {
            ShowMessage(message, 2);
        }

        private void ShowMessage(string message, int seconds)
        {
            MessageLabel.Text = message;
            MessageLabel.Top = 0;
            MessageLabel.Left = 0;
            MessagePanel.Height = MessageLabel.Height;
            MessagePanel.Width = MessageLabel.Width;
            MessagePanel.Top = 10;// (Height - MessageLabel.Height) / 2;
            MessagePanel.Left = (Width - MessageLabel.Width) / 2;
            MessagePanel.Visible = true;
            MessagePanel.BringToFront();
            MessageTimer.Interval = seconds * 1000;
            MessageTimer.Enabled = true;
        }

        private void MessageTimer_Tick(object sender, EventArgs e)
        {
            MessageTimer.Enabled = false;
            MessagePanel.Visible = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            if (StartTimer.Enabled)
            {
                StartTimer.Enabled = false;
                StartButton.Text = "Start";
            }
            else
            {
                if (StartImmediatelyRadioButton.Checked)
                {
                    DoStart();
                }
                else
                {
                    if (StartAtSpecificTimeRadioButton.Checked)
                    {
                        _startTime = StartTimePicker.Value;
                    }
                    else if (StartOnTheHourRadioButton.Checked)
                    {
                        _startTime = _nextHourTime;
                    }
                    else if (StartOnTheHalfHourRadioButton.Checked)
                    {
                        _startTime = _nextHalfHourTime;
                    }
                    else if (StartOnTheQuarterHourRadioButton.Checked)
                    {
                        _startTime = _nextQuarterHourTime;
                    }

                StartButton.Text = String.Format("CANCEL - starting at {0:hh:mm tt}", _startTime);
                StartTimer.Enabled = true;
                }
            }
        }

        private void DoStart()
        {
            StartTimer.Enabled = false;
            StartPanel.Visible = false;
            Text = string.Empty;
            ControlBox = false;
            WindowState = FormWindowState.Maximized;

            MainPanel.Width = Program.Config.ScreenSizeX;
            MainPanel.Height = Program.Config.ScreenSizeY;

            SetPanelSize();
            _controlManager = new ControlManager(Program.Config, MainPanel.Controls);
            _controlManager.Finished += ControlManager_Finished;
            _controlManager.Start(GetIteration());
        }

        private void StartTimer_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now >= _startTime)
            {
                DoStart();
            }
        }

        private uint GetIteration()
        {
            return Convert.ToUInt32(numericIteration.Value);
        }

        private uint IncrementAndGetIteration()
        {
            numericIteration.Value = numericIteration.Value + 1;
            return GetIteration();
        }

        private uint ResetAndGetIteration()
        {
            numericIteration.Value = 1.0m;
            return GetIteration();
        }
        
    }
}
